<template>
  <div class="account-login width-100 m-rem-t-24">
    <el-form ref="loginForm" :model="form" :rules="loginRules" class="form-con">
      <el-form-item prop="username">
        <el-input v-model.trim="form.username" placeholder="请输入手机号" maxlength="11"
                  @keyup.delete.native="userNameChange"
        >
          <div slot="prefix" class="w-rem-20 h-rem-36 flex row-center col-center">
            <img src="../../../assets/images/businessImages/login/phone.png" alt="" class="w-rem-20 h-rem-20 obj-fit-contain">
          </div>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model.trim="form.password" :type="passwordOpen ? 'password' : 'text'" placeholder="请输入密码"
                  @keyup.delete.native="passwordChange"
        >
          <div slot="prefix" class="w-rem-20 h-rem-36 flex row-center col-center">
            <img src="../../../assets/images/businessImages/login/password.png" alt="" class="w-rem-20 h-rem-20 obj-fit-contain">
          </div>
          <div slot="suffix" class="iconfonts w-rem-30" :class="passwordOpen ? 'icon-eye_off' : 'icon-eye-fill'"
               @click="passwordOpen = !passwordOpen"
          ></div>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model.trim="form.code" placeholder="请输入验证码" class="width-58" @keyup.enter.native="handleLogin">
          <div slot="prefix" class="w-rem-20 h-rem-36 flex row-center col-center">
            <img src="../../../assets/images/businessImages/login/vcode.png" alt="" class="w-rem-20 h-rem-20 obj-fit-contain">
          </div>
        </el-input>
        <img alt="" :src="codeUrl" class="width-34 h-rem-36 m-rem-l-10 b-r-rem-4" style="border: 0.1rem solid #D9D9D9;"
             @click="getCode"
        />
      </el-form-item>
      <!-- <el-checkbox v-model="save">记住密码</el-checkbox> -->
      <el-button type="primary" class="width-100 m-rem-t-18" @click="handleLogin">登录</el-button>
    </el-form>

    <!-- 选择租户方式 -->
    <tenantMethod ref="tenantMethod" @tenantMethodFun="tenantMethodFun" />
  </div>
</template>
<script>
import setMessage from '@/utils/publicUtils/message'
// Api
import { methodGetApi } from "@/api/publicApi"
// 组件
import tenantMethod from './tenantMethod/index.vue'
export default {
  name: 'Login',
  components: { tenantMethod },
  inject: {
    login: {
      default: () => ({})
    }
  }, // --> ------ form接值 +选择 弹窗 必加
  provide() {
    return {
      formProvide: this
    }
  },
  data() {
    return {
      codeUrl: '',
      save: false,
      form: {
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      passwordOpen: true,
      createVcode: null,
      loginRules: {
        username: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        // username: [ { required: false, msg: '手机号', trigger: 'blur', validator: (rule, value, callback) => this.regularFun(rule, value, callback, 'phone') }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      redirect: undefined,
      pcLogoBool: false,
      platformName: '',
      platformPrefixName: ''
    }
  },
  //   watch: {
  //     $route: {
  //       handler: function(route) {
  //         this.redirect = route.query && route.query.redirect
  //       },
  //       immediate: true
  //     }
  //   },
  mounted() {
    this.getCode()
  },
  created() {
    // 获取平台信息
    // getPlatform().then((res) => {
    //   this.platformName = res.data.platformName
    //   this.platformPrefixName = res.data.platformPrefixName
    //   const annexPath = res.data.annexPath
    //   localStorage.setItem('platformName', this.platformName)
    //   localStorage.setItem('platformPrefixName', this.platformPrefixName)
    //   localStorage.setItem('logoImg', annexPath)
    // })
    const loginInfo = localStorage.getItem('login')
    if (loginInfo != null && loginInfo !== '') {
      this.form = JSON.parse(loginInfo)
      // this.save = true
    }
  },
  methods: {
    // 输入框中的
    userNameChange() {
      this.form.userName = null
    },

    // 输入框中的
    passwordChange() {
      this.form.password = null
    },

    /**
     * @description: 点击登录
     * @author: 张佳敏
     * @return {*}
     */
    handleLogin() {
      if (!this.login.loading) {
        // 验证码正确后判断登录名和密码
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            methodGetApi('/verfiyCode',this.form).then((res) => {
              // 多租户使用 getTenantListByUserPhone
              // this.getTenantListByUserPhone()
              /*************************************************/
              // 默认登录
              this.LoginTo()
            }).catch(() => {
              this.login.loading = false
              this.getCode() // 重刷验证码
            })
          } else {
            return false
          }
        })
      }
    },

    /**
     * @description: 获取租户
     * @author: 张佳敏
     * @return {*}
     */
    getTenantListByUserPhone() {
      const data = { phone: this.form.username }
      methodGetApi('/tenant/getTenantListByUserPhone', data).then(res => {
        if (res.data.length > 1) {
          this.$refs['tenantMethod'].selectId = null // 赋值 对象数组
          this.$refs['tenantMethod'].dialogListVisibleBool = true
          this.$refs['tenantMethod'].dialogList = res.data
        } else if (res.data.length == 1) {
          // 数据 等于 1  租户id
          localStorage.setItem('tenantId', res.data[0].id)
          this.LoginTo()
        } else {
          this.msgAlt('账号不存在', 'error')
        }
      })
    },

    /**
     * @description: 选择租户回调
     * @author: 张佳敏
     * @param {*} data
     * @return {*}
     */
    tenantMethodFun(data) {
      this.$refs['tenantMethod'].dialogListVisibleBool = false
      this.LoginTo()
    },

    /**
     * @description: 真登录
     * @author: 张佳敏
     * @return {*}
     */
    LoginTo() {
      this.login.loading = true
      this.$store.dispatch('user/login', this.form).then(() => {
        console.log(111)
        this.saveLogin() // 保存登录信息
        console.log(222)

        // setMessage()
        console.log(33)

        // sunbin update 2021/10/15 16:48 防止路劲访问回到之前路径地址
        // this.redirect 历史路径
        // this.$router.push({ path: this.redirect || '/' })
        // this.$router.push({ path: '/' })
        // 时间 ：2022/11/18  张佳敏 修改 跳转地址
        // localStorage.setItem('indexPath', '/system/user')
        this.$router.push({ path: '/system/user' }).catch(()=>{})
      }).catch(() => {
        this.login.loading = false
        // this.getCode() // 重刷验证码
      })
    },

    /**
     * @description: 保存账户
     * @author: 张佳敏
     * @return {*}
     */
    saveLogin() {
      if (this.save) {
        const neeForm = {
          username: this.form.username,
          password: this.form.password
        }
        localStorage.setItem('login', JSON.stringify(neeForm))
      } else {
        localStorage.removeItem('login')
      }
    },

    /**
     * @description: 验证码
     * @author: 张佳敏
     * @return {*}
     */
    getCode() {
      methodGetApi('/captchaImage').then((res) => {
        this.$nextTick(() => {
          this.codeUrl = 'data:image/jpg;base64,' + res.img
          this.form.uuid = res.uuid
        })
      })
    }
  }
}
</script>
<style lang="scss">
    .account-login {
        .el-form-item__content {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .el-input__prefix {
            left: 1rem;
        }

        .el-input__inner {
            padding: 0rem 1.2rem 0rem 3.8rem;
            border: 0.1rem solid #D9D9D9;
        }
    }
</style>
